package com.itheima.imclient100.presenter.impl;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.itheima.imclient100.presenter.ConversationPresenter;
import com.itheima.imclient100.view.ConversationView;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * Created by fullcircle on 2017/7/4.
 */

public class ConversationPresenterImpl implements ConversationPresenter {
    private ConversationView conversationView;

    public ConversationPresenterImpl(ConversationView conversationView) {
        this.conversationView = conversationView;
    }

    /**
     *
     *  通知界面刷新数据
     *
     */
    @Override
    public void getConversation() {
        //从数据库获取会话信息
        Map<String, EMConversation> allConversations = EMClient.getInstance().chatManager().getAllConversations();
        //获取所有会话的集合
        Collection<EMConversation> values = allConversations.values();
        //转化成list
        List<EMConversation> conversations = new ArrayList<>(values);
        //按照时间先后顺序排序
        Collections.sort(conversations, new Comparator<EMConversation>() {
            @Override
            public int compare(EMConversation o1, EMConversation o2) {
                return (int) (o2.getLastMessage().getMsgTime()-o1.getLastMessage().getMsgTime());
            }
        });
        //通知界面刷新数据
        conversationView.onGetConversation(conversations);
    }

    /**
     *
     * //指定会话消息未读数清零
     * @param username
     */
    @Override
    public void markMessageAsReaded(String username) {
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(username);
        //指定会话消息未读数清零
        if(conversation !=null)
        conversation.markAllMessagesAsRead();
    }

    /**
     * 获取当前用户所有未读消息数量
     * @return
     */
    @Override
    public int getAllUnReadMessageNumber() {
        //获取当前用户所有未读消息数量
       return EMClient.getInstance().chatManager().getUnreadMessageCount();
    }

    /**
     * markAllConversationsAsRead 标记所有会话为已读
     *
     */
    @Override
    public void clearAllUnReadMessageNumber() {
        //markAllConversationsAsRead 标记所有会话为已读
        EMClient.getInstance().chatManager().markAllConversationsAsRead();
    }


}
